﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using System.Data.SqlTypes;
using System.Reflection;
using System.Runtime.Serialization;
using System.Runtime.Serialization.Formatters.Binary;
using System.IO;

namespace NSATBPortal
{
    public partial class TestCaseDetail : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if(!IsPostBack)
            {
                string sOp = Request.QueryString["Op"].ToString();
                string sVal = Request.QueryString["ID"].ToString();
                int iTestCaseID = int.Parse(sVal);

                if (sOp == "DefTestCase")
                {
                    // Fill TC Details
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        DataTable dtResults = objATBDB.GetDefTestCaseList(iTestCaseID);
                        TCNameValue.Text = dtResults.Rows[0]["Name"].ToString();
                        TCQCIDValue.Text = dtResults.Rows[0]["QCID"].ToString();
                        TCDescriptionValue.Text = dtResults.Rows[0]["Description"].ToString();
                        TCMaxTimeValue.Text = dtResults.Rows[0]["MaxExecutionTimeMins"].ToString();
                        if (TCMaxTimeValue.Text == "-1")
                            TCMaxTimeValue.Text = "Default";
                        TCTargetSystemValue.Text = dtResults.Rows[0]["TargetSystem"].ToString();
                    }

                    // Fill TC Steps
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        DataTable dtResults = objATBDB.GetDefTestCaseSteps(iTestCaseID);

                        int iRowCount = dtResults.Rows.Count;
                        int iColCount = dtResults.Columns.Count;
                        if (iRowCount == 0)
                            return;

                        for (int iRow = 0; iRow < iRowCount; iRow++)
                        {
                            TableRow tableRow = new TableRow();
                            tableSteps.Rows.Add(tableRow);

                            for (int iCol = 0; iCol < iColCount; iCol++)
                            {
                                string sValue = dtResults.Rows[iRow][iCol].ToString();
                                // first column
                                if (iCol == 0)
                                {
                                    // first row - even # means step name
                                    if(iRow % 2 == 0)
                                    {
                                        tableRow.Cells.Add(CreateStepCell("StepName", sValue));
                                    }
                                    else
                                    // otherwise, action word
                                    {
                                        tableRow.Cells.Add(CreateStepCell("ActionWord", sValue));
                                    }
                                }
                                else
                                {
                                    // if null, filler
                                    if (string.IsNullOrEmpty(sValue))
                                    {
                                        tableRow.Cells.Add(CreateFillerCell(1));
                                    }
                                    else
                                    {
                                        // first row - even # param name
                                        if (iRow % 2 == 0)
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ParamName", sValue));
                                        }
                                        else
                                        // otherwise, param value
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ParamValue", sValue));
                                        }
                                    }
                                }
                            }
                        }
                    }
                }
                // ResTestCase (Test Results)
                else
                {
                    // Update Header
                    subheader.HRef = "RunsJournalView.aspx?ID=" + Request.QueryString["ParentID"].ToString();
                    subheader.InnerText = "Runs Journal Item";

                    bool bEvidence = false;
                    // Fill TC Details
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        DataTable dtResults = objATBDB.GetRunsJournalTestCaseDetail(iTestCaseID);
                        TCNameValue.Text = dtResults.Rows[0]["Name"].ToString();
                        TCQCIDValue.Text = dtResults.Rows[0]["QCID"].ToString();
                        TCDescriptionValue.Text = dtResults.Rows[0]["Description"].ToString();
                        TCMaxTimeValue.Text = dtResults.Rows[0]["MaxExecutionTimeMins"].ToString();
                        if (TCMaxTimeValue.Text == "-1")
                            TCMaxTimeValue.Text = "Default";
                        string sBoolVal = dtResults.Rows[0]["Evidence"].ToString();
                        bEvidence = (sBoolVal.ToLower() == "true");
                        TCTargetSystemValue.Text = dtResults.Rows[0]["TargetSystem"].ToString();
                        TCResultRow.Visible = true;
                        TCResultValue.Text = dtResults.Rows[0]["Result"].ToString();
                        if (!TCResultValue.Text.ToLower().Contains("pass"))
                            TCResultValue.BackColor = StepTmpl_ResultFail.BackColor;

                        string sErrorMessage = dtResults.Rows[0]["ErrorMessage"].ToString();
                        if(!string.IsNullOrEmpty(sErrorMessage))
                        {
                            TCErrorHeaderRow.Visible = true;
                            TCErrorValueRow.Visible = true;
                            TCErrorValue.Text = sErrorMessage;
                        }
                    }

                    // Fill TC Steps

                    DataTable dtStepMetaData;
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        dtStepMetaData = objATBDB.GetRunsJournalTestCaseStepsData(iTestCaseID);
                    }
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        DataTable dtResults = objATBDB.GetRunsJournalTestCaseSteps(iTestCaseID);

                        int iRowCount = dtResults.Rows.Count;
                        int iColCount = dtResults.Columns.Count;
                        if (iRowCount == 0)
                            return;

                        for (int iRow = 0; iRow < iRowCount; iRow++)
                        {
                            TableRow tableRow = new TableRow();
                            tableSteps.Rows.Add(tableRow);

                            for (int iCol = 0; iCol < iColCount; iCol++)
                            {
                                string sValue = dtResults.Rows[iRow][iCol].ToString();
                                // first or second column
                                if (iCol <= 1)
                                {
                                    if (iCol == 0)
                                    {
                                        // first row - even # means result
                                        if (iRow % 2 == 0)
                                        {
                                            if(sValue.ToLower().Contains("pass"))
                                                tableRow.Cells.Add(CreateStepCell("ResultPass", sValue));
                                            else
                                                if (sValue.ToLower().Contains("no") || sValue.ToLower().Contains("skip"))
                                                    tableRow.Cells.Add(CreateStepCell("ResultNoRun", sValue));
                                                else
                                                    tableRow.Cells.Add(CreateStepCell("ResultFail", sValue));
                                        }
                                        else
                                        // otherwise, run time
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ResultSecs", sValue));
                                        }
                                    }
                                    else
                                    {
                                        // first row - even # means step name
                                        if (iRow % 2 == 0)
                                        {
                                            tableRow.Cells.Add(CreateStepCell("StepName", sValue));
                                        }
                                        else
                                        // otherwise, action word
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ActionWord", sValue));
                                        }
                                    }
                                }
                                else
                                {
                                    // if null, filler
                                    if (string.IsNullOrEmpty(sValue))
                                    {
                                        tableRow.Cells.Add(CreateFillerCell(1));
                                    }
                                    else
                                    {
                                        // first row - even # param name
                                        if (iRow % 2 == 0)
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ParamName", sValue));
                                        }
                                        else
                                        // otherwise, param value
                                        {
                                            tableRow.Cells.Add(CreateStepCell("ParamValue", sValue));
                                        }
                                    }
                                }

                            }
                            if (iRow > 0)
                            {
                                if (iRow % 2 == 1)
                                {
                                    // results text row needs to be here
                                    string sResultText = dtStepMetaData.Rows[((iRow + 1) / 2) - 1]["ResultText"].ToString();
                                    tableRow = new TableRow();
                                    tableSteps.Rows.Add(tableRow);
                                    tableRow.Cells.Add(CreateStepCell("ResultText", "Actual Result: " + sResultText, false, 8));
                                    for (int iLoop = 0; iLoop < (iColCount - 8); iLoop++)
                                    {
                                        tableRow.Cells.Add(CreateFillerCell(1));
                                    }

                                    // evidence row(s) need to be here
                                    bool bStepEvidence = false;
                                    bStepEvidence = bool.TryParse(dtStepMetaData.Rows[((iRow + 1) / 2) - 1]["Evidence"].ToString(), out bStepEvidence);
                                    if (bStepEvidence)
                                    {
                                        int iResTestStepID = int.Parse(dtStepMetaData.Rows[((iRow + 1) / 2) - 1]["ResTestStepID"].ToString());
                                        DataTable dtTSEvidence = objATBDB.GetRunsJournalTestStepEvidenceList(iResTestStepID);

                                        for (int iTSRow = 0; iTSRow < dtTSEvidence.Rows.Count; iTSRow++)
                                        {
                                            tableRow = new TableRow();
                                            tableSteps.Rows.Add(tableRow);

                                            tableRow.Cells.Add(
                                                CreateStepEvidenceCell(
                                                        dtTSEvidence.Rows[iTSRow]["ResTestEvidenceID"].ToString(),
                                                        dtTSEvidence.Rows[iTSRow]["FileName"].ToString(),
                                                        dtTSEvidence.Rows[iTSRow]["Description"].ToString(),
                                                        8
                                                    )
                                                );
                                            for (int iLoop = 0; iLoop < (iColCount - 8); iLoop++)
                                            {
                                                tableRow.Cells.Add(CreateFillerCell(1));
                                            }
                                        }
                                    }  

                                    // create a row with just border
                                    tableRow = new TableRow();
                                    tableSteps.Rows.Add(tableRow);
                                    for (int iLoop = 0; iLoop < iColCount; iLoop++)
                                    {
                                        tableRow.Cells.Add(CreateBorderCell(1));
                                    }
                                }
                            }
                        }
                    }
                    // Evidence Row(s)
                    using (ATBSchemaDB objATBDB = new ATBSchemaDB())
                    {
                        DataTable dtTCEvidence = objATBDB.GetRunsJournalTestCaseEvidenceList(iTestCaseID);

                        if(dtTCEvidence.Rows.Count > 0)
                            tableEvidence.Visible = true;

                        for (int iRow = 0; iRow < dtTCEvidence.Rows.Count; iRow++)
                        {

                            TableRow oNewEvidenceRow = new TableRow(); 
                            BuildTestEvidenceRow( oNewEvidenceRow,
                                        dtTCEvidence.Rows[iRow]["ResTestEvidenceID"].ToString(),
                                        dtTCEvidence.Rows[iRow]["Name"].ToString(),
                                        dtTCEvidence.Rows[iRow]["DataType"].ToString(),
                                        dtTCEvidence.Rows[iRow]["FileName"].ToString(),
                                        dtTCEvidence.Rows[iRow]["Description"].ToString()
                                    );
                            oNewEvidenceRow.Visible = true;
                            tableEvidence.Rows.Add(oNewEvidenceRow);
                        }
                        TDResProofColTemplate.Visible = false;

                    }

                }

            }
        }

        /*protected void RunsGrid_Init(object sender, EventArgs e)
        {
            DataTable dtResults;
            using (ATBSchemaDB objATBDB = new ATBSchemaDB())
            {
                dtResults = objATBDB.GetRunsList();
            }

            RunsGrid.DataSource = dtResults;
            RunsGrid.DataBind();
        }*/

        public TableCell CreateStepCell(string sType)
        {
            return (CreateStepCell(sType, string.Empty));
        }
        public TableCell CreateStepCell(string sType, string sText)
        {
            return(CreateStepCell(sType, sText, true, -1));
        }
        public TableCell CreateStepCell(string sType, string sText, bool bLimitText, int iColSpan)
        {
            
            TableCell oSourceCell;
            switch (sType)
            {
                case "StepName":
                    oSourceCell = StepTmpl_StepName;
                    break;
                case "ParamName":
                    oSourceCell = StepTmpl_ParamName;
                    break;
                case "ParamValue":
                    oSourceCell = StepTmpl_ParamValue;
                    break;
                case "ActionWord":
                    oSourceCell = StepTmpl_ActionWord;
                    break;
                case "ResultSecs":
                    oSourceCell = StepTmpl_ResultSecs;
                    break;
                case "ResultPass":
                    oSourceCell = StepTmpl_ResultPass;
                    break;
                case "ResultNoRun":
                    oSourceCell = StepTmpl_ResultNoRun;
                    break;
                case "ResultFail":
                    oSourceCell = StepTmpl_ResultFail;
                    break;
                case "ResultText":
                    oSourceCell = StepTmpl_ResultText;
                    break;
                case "ResultProof":
                    oSourceCell = StepTmpl_ResultProof;
                    break;
                default:
                    throw new Exception("Invalid cell type provided");

            }

            TableCell oNewCell = new TableCell()
            {
                BackColor=oSourceCell.BackColor,
                ForeColor=oSourceCell.ForeColor,
                BorderColor=oSourceCell.BorderColor,
                BorderStyle=oSourceCell.BorderStyle,
                BorderWidth=oSourceCell.BorderWidth,
                Wrap=oSourceCell.Wrap,
                VerticalAlign=oSourceCell.VerticalAlign,
                Width=oSourceCell.Width,
                Text=oSourceCell.Text
            };
            oNewCell.Font.Bold = oSourceCell.Font.Bold;
            oNewCell.Font.Size = oSourceCell.Font.Size;

            if (!string.IsNullOrEmpty(sText))
            {
                if (bLimitText)
                {
                    if (sText.Length > 25)
                    {
                        oNewCell.ToolTip = sText;
                        sText = sText.Substring(0, 25) + "...";
                    }
                }
            }
            oNewCell.Text = Server.HtmlEncode(sText);
            if (iColSpan > 0)
                oNewCell.ColumnSpan = iColSpan;
            return (oNewCell);
        }
        public TableCell CreateFillerCell(int iSpan)
        {

            TableCell oSourceCell = StepTmpl_Filler;

            TableCell oNewCell = new TableCell()
            {
                BackColor=oSourceCell.BackColor,
                ForeColor=oSourceCell.ForeColor,
                BorderColor=oSourceCell.BorderColor,
                BorderStyle=oSourceCell.BorderStyle,
                BorderWidth=oSourceCell.BorderWidth,
                Wrap=oSourceCell.Wrap,
                VerticalAlign=oSourceCell.VerticalAlign,
                Width=oSourceCell.Width,
                Height=1,
                //Text=oSourceCell.Text,
                ColumnSpan = iSpan
            };
            
            return (oNewCell);
        }
        public TableCell CreateBorderCell(int iSpan)
        {

            TableCell oSourceCell = StepTmpl_Filler;

            TableCell oNewCell = new TableCell()
            {
                BackColor = System.Drawing.Color.SlateGray,
                ForeColor = oSourceCell.ForeColor,
                BorderColor = oSourceCell.BorderColor,
                BorderStyle = oSourceCell.BorderStyle,
                BorderWidth = oSourceCell.BorderWidth,
                Wrap = oSourceCell.Wrap,
                VerticalAlign = oSourceCell.VerticalAlign,
                Width = oSourceCell.Width,
                Height = 1,
                //Text=oSourceCell.Text,
                ColumnSpan = iSpan
            };

            return (oNewCell);
        }
        public TableRow BuildTestEvidenceRow(TableRow oEvidenceRow, string sID, string sName, string sType, string sFilename, string sDescription)
        {
           
            // ID
            {
                TableCell oSourceCell = TCResProofIDColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = Server.HtmlEncode(sID)
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;
                oEvidenceRow.Cells.Add(oNewCell);
            }
            // Open
            {
                TableCell oSourceCell = TCResProofOpenColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = oSourceCell.Text
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;

                // build link
                oNewCell.Text = oNewCell.Text.Replace("?ID=", "?ID=" + sID);
                oNewCell.Text = oNewCell.Text.Replace("&Filename=", "&Filename=" + Server.UrlEncode(sFilename));
                oEvidenceRow.Cells.Add(oNewCell);
            }
            // Name
            {
                TableCell oSourceCell = TCResProofNameColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = Server.HtmlEncode(sName)
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;
                oEvidenceRow.Cells.Add(oNewCell);
            }
            // Type
            {
                TableCell oSourceCell = TCResProofTypeColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = Server.HtmlEncode(sType)
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;
                oEvidenceRow.Cells.Add(oNewCell);
            }
            // Filename
            {
                TableCell oSourceCell = TCResProofFilenameColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = Server.HtmlEncode(sFilename)
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;
                oEvidenceRow.Cells.Add(oNewCell);
            }
            // Description
            {
                TableCell oSourceCell = TCResProofDescriptionColValue;
                TableCell oNewCell = new TableCell()
                {
                    BackColor = oSourceCell.BackColor,
                    ForeColor = oSourceCell.ForeColor,
                    BorderColor = oSourceCell.BorderColor,
                    BorderStyle = oSourceCell.BorderStyle,
                    BorderWidth = oSourceCell.BorderWidth,
                    Wrap = oSourceCell.Wrap,
                    VerticalAlign = oSourceCell.VerticalAlign,
                    Width = oSourceCell.Width,
                    Visible = oSourceCell.Visible,
                    Text = Server.HtmlEncode(sDescription)
                };
                oNewCell.Font.Bold = oSourceCell.Font.Bold;
                oNewCell.Font.Size = oSourceCell.Font.Size;
                oEvidenceRow.Cells.Add(oNewCell);
            }
            
            return (oEvidenceRow);
        }

        public TableCell CreateStepEvidenceCell(string sID, string sFilename, string sDescription, int iColSpan)
        {
            TableCell oNewCell = CreateStepCell("ResultProof", "", false, iColSpan);
            oNewCell.Text = StepTmpl_ResultProof.Text;

            // build link
            oNewCell.Text = oNewCell.Text.Replace("?ID=", "?ID=" + sID);
            oNewCell.Text = oNewCell.Text.Replace("&Filename=", "&Filename=" + Server.UrlEncode(sFilename));
            oNewCell.Text = oNewCell.Text.Replace("!Filename", Server.HtmlEncode(sFilename));
            oNewCell.Text = oNewCell.Text.Replace("!Description", Server.HtmlEncode(sDescription));
            
            return (oNewCell);
        }
    }
}